
import util from '../../utils/canvasUtil'
const common = require('../../js/config.js');
const app = getApp();
Page({
  data: {
    windowWidth: 0,
    windowHeight: 0,
    contentHeight: 0,
    footer: '',
    offset: 0,
    lineHeight: 30,
    sentenceHeight: 220,
    organHeight: 0,
    cardCodeHeight: 120,
    posterData: {}
  },
  onLoad: function (options) {
    let that = this;
    console.log(options.objectId)
    that.setData({
      objectId: options.objectId
    });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          offset: 60
        });
      }
    });
  },
  onShow: function () {
    let that = this;
    wx.request({
      url:  common.formal +'/selectPosterObjectTransInit.form',
      data: {
        objectId: that.data.objectId
      },
      success(res) {
        let posterData = res.data.data;
        that.setData({
          posterData: posterData,
          tel:posterData.enterprisePhone==null?'暂未填写': posterData.enterprisePhone,
          add:posterData.enterpriseAddr==null?'暂未填写':posterData.enterpriseAddr
        });
        console.log(posterData);
        // if(posterData.avatarUrl==null){
        //   posterData.avatarUrl==''
        // }
        wx.downloadFile({
          url: posterData.avatarUrl,//头像下载
          success: res => {
            if (res.statusCode === 200) {
              console.log(res.tempFilePath)
              that.setData({
                locolAvatarUrl: res.tempFilePath//将下载下来的地址给data中的变量变量
              });
              wx.downloadFile({
                url: posterData.sentence.sentenceUrl,//每日一句主图下载
                success: res => {
                  if (res.statusCode === 200) {
                    console.log(res.tempFilePath)
                    that.setData({
                      locolSentenceUrl: res.tempFilePath//将下载下来的地址给data中的变量变量
                    });
                    wx.downloadFile({
                      url: posterData.cardCodeUrl,//名片码下载
                      success: res => {
                        if (res.statusCode === 200) {
                          console.log(res.tempFilePath)
                          that.setData({
                            locolCardCodeUrl: res.tempFilePath//将下载下来的地址给data中的变量变量
                          });
                          that.createNewImg();//画图
                        }
                      }, fail: res => {
                        console.log(res);
                      }
                    });
                  }
                }, fail: res => {
                  console.log(res);
                }
              });
            }
          }, fail: res => {
            console.log(res);
          }
        });

      }
    })


  },
  // fillStyle设置或返回用于填充绘画的颜色、渐变或模式
  // rec创建矩形（x,y,width,height）x矩形左上角的x坐标,y矩形右上角的y坐标，width矩形的宽度（以像素计），height矩形的高度(以像素计)
  // fillRec绘制‘被填充的’矩形
  drawSquare: function (ctx, height) { 
    let that = this;
    console.log(height)
    ctx.rect(30, 10, that.data.windowWidth - 60, height)
    // ctx.setFillStyle('rgba(0,0,0,0.1)')
    ctx.setFillStyle("#fefefe");
    ctx.fill()
  },
  drawSquare1: function (ctx, height) {
    ctx.beginPath();
    let that = this;
    console.log(height)
    ctx.rect(50, 10, that.data.windowWidth - 100, height - 10)
    // ctx.setFillStyle('rgba(0,0,0,0.1)')
    ctx.setFillStyle("#f9f9f9");
    ctx.fill()
    ctx.closePath();
  },
  drawSquare2: function (ctx, height) {
    ctx.beginPath();
    let that = this;
    console.log(height)
    ctx.rect(50, 10, that.data.windowWidth - 100, height - 10)
    ctx.setFillStyle('rgba(0,0,0,0.1)')
    console.log(that.data.windowWidth - 100)
    // ctx.setFillStyle("#f9f9f9");
    ctx.fill()
    ctx.closePath();
  },
  /**
 * 渲染文字
 *0
 * @param {Object} obj
 */
  drawText: function (ctx, obj) {
    if (obj == null) {
      return;
    }
    console.log('渲染文字')
    ctx.save();
    ctx.setFillStyle(obj.color);
    ctx.setFontSize(obj.size);
    ctx.setTextAlign(obj.align);
    ctx.setTextBaseline(obj.baseline);
    if (obj.bold) {
      console.log('字体加粗')
      ctx.fillText(obj.text, obj.x, obj.y - 0.5);
      ctx.fillText(obj.text, obj.x - 0.5, obj.y);
    } else {
      ctx.fillText(obj.text, obj.x, obj.y);
    }
    ctx.restore();
  },
  /**
 * 文本换行
 *
 * @param {Object} obj
 */
  textWrap: function (ctx, obj) {
    if (obj == null) {
      return;
    }
    let that = this;
    console.log('文本换行')
    //width文本区域宽度
    var td = Math.ceil(obj.width / (obj.size));
    var tr = Math.ceil(obj.text.length / td);
    for (var i = 0; i < tr; i++) {
      var txt = {
        x: obj.x,
        //height文本行高
        y: obj.y + (i * obj.height),
        color: obj.color,
        size: obj.size,
        align: obj.align,
        baseline: obj.baseline,
        text: obj.text.substring(i * td, (i + 1) * td),
        bold: obj.bold
      };
      if (i > 0) {
        if (obj.tag == '1') {
          txt.y = txt.y - 10;
        } else {
          txt.y = txt.y - 10;
          txt.x = txt.x + 27;
        }
      }
      //line最多显示几行
      if (i < obj.line) {
        if (i == obj.line - 1) {
          if (obj.bold == true && txt.text.length > 18) {
            txt.text = txt.text.substring(0, txt.text.length - 3) + '......';
          } else if (obj.bold == false && txt.text.length > 30) {
            txt.text = txt.text.substring(0, txt.text.length - 3) + '......';
          }
        }
        that.drawText(ctx, txt);
      }
    }
  },
  returnTitle: function (x, y, color, size, align, baseline, text, bold) {
    if (text == undefined) {
      return null;
    }
    let title = {
      x: x,//绘制文本的左上角x坐标位置
      y: y,//绘制文本的左上角y坐标位置
      color: color,//字体的颜色
      size: size,//字体的字号
      align: align,//文字的对齐，可选值 'left'、'center'、'right'
      baseline: baseline,//设置文字的水平对齐，可选值 'top'、'bottom'、'middle'、'normal'
      text: text,//内容
      bold: bold//是否加粗
    };
    return title;
  },
  returnDetails: function (x, y, color, size, align, baseline, text, bold, width, height, line, tag) {
    let that = this;
    if (text == undefined) {
      return null;
    }
    let organHeight = that.data.organHeight;
    if (tag == '1') {
      y = y;
      console.log(y)
    } else if (tag == '2') {
      organHeight = organHeight + height;
      organHeight = organHeight - 10;
      that.setData({ organHeight: organHeight });
      y = y + organHeight;
      console.log(y)
    } else {
      y = y + organHeight;
    }
    var td = Math.ceil(width / (size));
    var tr = Math.ceil(text.length / td);
    if (tag != "1") {
      for (var i = 0; i < tr; i++) {
        if (i > 0) {
          organHeight = organHeight + height;
          organHeight = organHeight - 10;
          that.setData({ organHeight: organHeight });
        }
      }
    }
    console.log(organHeight)
    let details = {
      x: x,//绘制文本的左上角x坐标位置
      y: y,//绘制文本的左上角y坐标位置
      color: color,//字体的颜色
      size: size,//字体的字号
      align: align,//文字的对齐，可选值 'left'、'center'、'right'
      baseline: baseline,//设置文字的水平对齐，可选值 'top'、'bottom'、'middle'、'normal'
      text: text,//内容
      bold: bold,//是否加粗
      width: width,//文本区域宽度
      height: height,//文本行高
      line: line,//最多显示几行
      tag: tag//最多显示几行
    };

    return details;
  },
  createNewImg: function () {
    let that = this;
    let posterData = that.data.posterData;
    console.log(posterData.avatarUrl);
    let sentenceHeight = that.data.sentenceHeight;//每日一句主图高度
    let cardCodeHeight = that.data.cardCodeHeight;//底部名片码模块高度
    let ctx = wx.createCanvasContext('myCanvas');
    console.log(sentenceHeight)
    console.log(cardCodeHeight)
    console.log(organHeight)
    //个人名片信息
    let objectName = that.returnDetails(that.data.offset + 70, sentenceHeight+5,
      '#323232', 15, 'left','top', posterData.objectName, true,
      that.data.windowWidth - 100, 30, 1, '2');
    let position = that.returnDetails(that.data.offset + 140, sentenceHeight+5 + 3,
      '#323232', 11, 'left', 'top', posterData.position, false,
      that.data.windowWidth - 100, 30, 1, false);
    let phone = that.returnDetails(that.data.offset + 70, sentenceHeight+5,
      '#323232', 11, 'left', 'top', 'Mobile:' + posterData.phone, false,
      that.data.windowWidth - 100, 30, 1, '2');
    let visitedNum = that.returnDetails(that.data.offset + 70, sentenceHeight+5,
      '#323232', 11, 'left', 'top', '访客:' + posterData.visitedNum, false,
      that.data.windowWidth - 100, 30, 1, '2');
    // 企业/机构信息
    let enterpriseName = that.returnDetails(that.data.offset, sentenceHeight,
      '#323232', 15, 'left', 'top', posterData.enterpriseName, true,
      that.data.windowWidth - 100, 30, 1, '2');
    let enterprisePhone = that.returnDetails(that.data.offset, sentenceHeight,
      '#323232', 11, 'left', 'top', 'Tel: ' +that.data.tel, false,
      that.data.windowWidth - 100, 30, 1, '2');
    let enterpriseAddr = that.returnDetails(that.data.offset, sentenceHeight,
      '#323232', 11, 'left', 'top', 'Add: ' +that.data.add, false,
      that.data.windowWidth - 100, 30, 2, '2');
    let organHeight = that.data.organHeight;//中间模块动态高度
    organHeight = organHeight + 35;//中间模块底部提供部分留白
    that.setData({ organHeight: organHeight });
    console.log(organHeight)
    let contentHeight = sentenceHeight + organHeight + cardCodeHeight;
    //底部白板
    that.drawSquare(ctx, contentHeight);
    //第二层蒙板
    that.drawSquare1(ctx, contentHeight - cardCodeHeight);
    ctx.drawImage(that.data.locolSentenceUrl, 50, 10, that.data.windowWidth - 100, sentenceHeight);
    ctx.drawImage(that.data.locolAvatarUrl, 60, 25 + sentenceHeight, 50, 50);
    ctx.drawImage(that.data.locolCardCodeUrl, that.data.windowWidth - that.data.offset - 100, contentHeight - cardCodeHeight + 10, 100, 100);
    //第三层蒙板
    that.drawSquare2(ctx, 115);
    //个人名片信息(此处为动态画法，高度随内容的增加而改变)
    that.textWrap(ctx, objectName);
    that.textWrap(ctx, position);
    that.textWrap(ctx, phone);
    that.textWrap(ctx, visitedNum);
    // 企业/机构信息(此处为动态画法，高度随内容的增加而改变)
    that.textWrap(ctx, enterpriseName);
    that.textWrap(ctx, enterprisePhone);
    that.textWrap(ctx, enterpriseAddr);
    //底部名片码信息(此处为静态画法)
    let cardObjectName = that.returnTitle(that.data.offset, contentHeight - cardCodeHeight + 25,
      '#323232', 11, 'left', 'top', '这是' + posterData.objectName + '专属小程序码', false);
    let cardContent1 = that.returnTitle(that.data.offset, contentHeight - cardCodeHeight + 45,
      '#323232', 11, 'left', 'top', '长按可以识别保存名片', true);
    let cardContent2 = that.returnTitle(that.data.offset, contentHeight - cardCodeHeight + 70,
      '#323232', 10, 'left', 'top', '保存后可直接分享朋友圈', false);
    that.drawText(ctx, cardObjectName);
    that.drawText(ctx, cardContent1);
    that.drawText(ctx, cardContent2);
    //每日一句(此处为静态画法)
    let posterDay = that.returnTitle(that.data.offset, 25,
      '#fff', 30, 'left', 'top', posterData.posterDay, true);
    let posterMonth = that.returnTitle(that.data.offset + 40, 25,
      '#fff', 12, 'left', 'top', posterData.posterMonth + '月', false);
    let posterWeek = that.returnTitle(that.data.offset + 40, 40,
      '#fff', 12, 'left', 'top', posterData.posterWeek, false);
    let sentenceContent = that.returnDetails(that.data.offset, 65,
      '#fff', 13, 'left', 'top', posterData.sentence.sentenceContent, false,
      that.data.windowWidth - 130, 30, 2, '1');
    that.drawText(ctx, posterDay);
    that.drawText(ctx, posterMonth);
    that.drawText(ctx, posterWeek);
    that.textWrap(ctx, sentenceContent);


    that.setData({ contentHeight: contentHeight });
    ctx.draw();
  },

  savePic: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: that.data.windowWidth,
      height: that.data.contentHeight,
      canvasId: 'myCanvas',
      success: function (res) {
        util.savePicToAlbum(res.tempFilePath)
      }
    })
  }
});